package com.flyme.module.base.provider.controller;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.flyme.common.core.aliyun.sms.AliSmsUtil;
import com.flyme.common.core.aliyun.sms.SmsTempEnum;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.utils.ApiAssert;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.api.SysCompanyRemoteService;
import com.flyme.module.base.client.entity.SysCompany;
import com.flyme.module.base.client.entity.SysUser;
import com.flyme.module.base.client.entity.SysVip;
import com.flyme.module.base.client.entity.SystemAccount;
import com.flyme.module.base.provider.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业管理
 *
 * @author zyf
 */
@Api(tags = "企业管理")
@RestController
public class SysCompanyController extends BaseController<SysCompanyService, SysCompany> implements SysCompanyRemoteService {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysVipService vipService;
    @Autowired
    private SysAccountService accountService;
    @Autowired
    private SysOperationlogService sysOperationlogService;


    /**
     * 企业列表
     *
     * @return
     */
    @ApiOperation(value = "企业列表", notes = "企业列表")
    @Override
    public ResultBody list(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysCompany company) {
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("c.id", "c.compName", "c.status", "c.compEmail", "c.address", "v.createTime", "c.compTel", "c.compLogo", "c.linkMan", "c.staffNum",
            "CASE WHEN c.status=0 THEN c.befVipTime ELSE v.expiryDate END expiryDate");
        cq.createAlias("vip", "v");
        cq.like("compName", company.getCompName());
        cq.like("compTel", company.getCompTel());
        cq.like("linkMan", company.getLinkMan());
        PqGrid pqGrid = bizService.pageList(cq);
        return ResultBody.success(pqGrid);
    }


    /**
     * 查询用户所属企业
     *
     * @return
     */
    @ApiOperation(value = "查询用户所属企业")
    @Override
    public ResultBody selectByUserId(@PathVariable Long userId) {

        return ResultBody.success(null);
    }

    @ApiOperation(value = "添加企业", notes = "添加企业")
    @Override
    public ResultBody add(@ModelAttribute SysCompany company) {
        company.setExpiryDate(company.getExpiryDate() + " 01:01:01");
        Boolean tag = bizService.add(company);
        if (tag) {
            Map<String, String> params = new HashMap<>();
            params.put("compName", company.getCompName());
            AliSmsUtil.sendSmsCode(SmsTempEnum.REGCOMPANY, company.getCompTel(), params);
            sysOperationlogService.addOperation("添加企业："+company.getCompName());
            return ResultBody.success("添加成功");
        } else {
            return ResultBody.failed("添加失败,手机号已存在");
        }
    }

    @ApiOperation(value = "更新企业", notes = "更新企业")
    @Override
    public ResultBody update(@ModelAttribute SysCompany company) {
        Boolean tag = bizService.update(company);
        if (tag) {
            return ResultBody.success("更新成功");
        } else {
            return ResultBody.failed("更新失败,手机号已存在");
        }
    }

    @ApiOperation(value = "删除企业", notes = "删除企业")
    @Override
    public ResultBody delByIds(@RequestParam String[] ids) {
        List<String> list = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(ids)) {
            for (String id : ids) {
                SysCompany company = bizService.getById(Long.parseLong(id));
                String mobile = company.getCompTel();
                SystemAccount account = accountService.findByAccount(mobile);
                if (ObjectUtils.isNotEmpty(account)) {
                    Long userId = account.getUserId();
                    accountService.removeById(account.getId());
                    userService.removeById(userId);
                }
                list.add(company.getCompName());
            }
        }
        Boolean tag = bizService.delByIds(ids);
        if(tag){
            for(String compName : list){
                sysOperationlogService.addOperation("删除企业："+compName);
            }
        }
        UpdateWrapper uw = new UpdateWrapper<SysUser>();
        uw.set(true, "companyId", null).in("companyId", ids);
        userService.update(uw);
        return ResultBody.success(tag);
    }

    @Override
    public ResultBody get(@PathVariable Long id) {
        SysCompany company = bizService.getById(id);
        SysVip vip = vipService.getCompanyVip(id);
        if(company.getStatus().equals(0)){//禁用状态中，显示记录时间
            company.setExpiryDate(company.getBefVipTime());
        }else{
            company.setExpiryDate(vip.getExpiryDate());
        }
        return ResultBody.success(company);
    }

    /**
     * 企业端登录判断使用
     */
    public ResultBody getLogin(@PathVariable Long id) {
        SysCompany company = bizService.getById(id);
        SysVip vip = vipService.getCompanyVip(id);
        if(company.getStatus().equals(0)){//禁用
            return  ResultBody.failed("账号已被禁用，请联系平台管理员");
        }
        Long a = DateUtil.between(DateUtil.date(), DateUtil.parseDateTime(vip.getExpiryDate()), DateUnit.MINUTE, false);
        if (a < 0) {//当前日期大于vip到期时间
            return  ResultBody.failed("会员已到期");
        }
        return ResultBody.success(company);
    }


    @ApiOperation(value = "添加企业员工")
    @Override
    public ResultBody adduser(@ModelAttribute SysUser user) {
        SysUser searchUser = userService.findByUserName(user.getUserName());
        ApiAssert.notNull("用户不存在", searchUser);
        Long companyId = searchUser.getCompanyId();
        if (ObjectUtils.isNotEmpty(companyId) && companyId.equals(user.getCompanyId())) {
            ApiAssert.isNull("用户已添加", companyId);
        } else {
            ApiAssert.isNull("用户已关联其他公司", companyId);
        }
        searchUser.setCompanyId(user.getCompanyId());
        boolean tag = userService.saveOrUpdate(searchUser);
        return ResultBody.ok("添加成功").setData(tag);
    }

    @ApiOperation(value = "删除企业员工", notes = "删除企业员工")
    @Override
    public ResultBody delByUserIds(@RequestParam String[] userIds) {
        UpdateWrapper uw = new UpdateWrapper<SysUser>();
        uw.set(true, "companyId", null).in("id", userIds);
        userService.update(uw);
        return ResultBody.success(true);
    }

    @ApiOperation(value = "修改企业状态", notes = "修改企业状态")
    @Override
    public ResultBody setStatus(@RequestParam Long id, @RequestParam Integer status) {
        SysCompany company = bizService.getById(id);
        company.setStatus(status);
        SysVip vip = vipService.getCompanyVip(id);
        if(status.equals(0)){//禁用时
            company.setBefVipTime(vip.getExpiryDate());
            vip.setExpiryDate("1990-01-01 01:01:01");
        }else{//启用
            vip.setExpiryDate(company.getBefVipTime());
        }
        vipService.saveOrUpdate(vip);
        boolean tag = bizService.saveOrUpdate(company);
        if (tag) {
            return ResultBody.success("更新成功");
        } else {
            return ResultBody.failed("更新失败");
        }
    }

}
